import { defineStore } from 'pinia';
import { computed, reactive, ref } from 'vue';

export const useRatingStore = defineStore('rating', () => {
  const pageNum = ref(1);
  const ratingList = reactive([]);
  const pageSize = ref(12);
  const total = ref(0);
  const hasMore = computed(() => ratingList.length < total.value);
  
  // 添加评分列表（去重）
  const addRatingList = (item) => {
    // 避免重复添加
    const exists = ratingList.some(rating => rating._id === item._id);
    if (!exists) {
      ratingList.push(item);
      total.value++;
    }
  };
  
  // 批量添加评分列表
  const addRatingListBatch = (items) => {
    items.forEach(item => addRatingList(item));
  };
  
  // 重置分页
  const resetPagination = () => {
    pageNum.value = 1;
    ratingList.length = 0; // 清空数组
    total.value = 0;
  };
  
  // 设置总数
  const setTotal = (count) => {
    total.value = count;
  };
  
  // 下一页
  const nextPage = () => {
    pageNum.value++;
  };
  
  // 检查是否已评分
  const isRated = (wallpaperId) => {
    return ratingList.some(item => item._id === wallpaperId);
  };
  
  // 获取评分
  const getRating = (id) => {
    const rating = ratingList.find(rating => rating._id === id);
    return rating ? rating.userScore : null;
  };
  
  return {
    ratingList,
    pageNum,
    pageSize,
    total,
    hasMore,
    addRatingList,
    addRatingListBatch,
    resetPagination,
    setTotal,
    nextPage,
    isRated,
    getRating
  };
}, {
  persist: {
    key: 'rating-store',
    paths: ['ratingList', 'total']
  }
});